//
//  SGSAppDelegate.m
//  RapidSquare
//
//  Created by German on 27.08.14.
//  Copyright (c) 2014 RapidSquare. All rights reserved.
//

#import "SGSAppDelegate.h"
#import <FacebookSDK/FacebookSDK.h>
#import <GooglePlus/GooglePlus.h>
#import "SGSUtils.h"
#import "SGSModelsManager.h"


NSString * const receivedRemoteNotification = @"receivedRemoteNotification";

@interface SGSAppDelegate ()

@property (strong, nonatomic) UIActivityIndicatorView * spinner;
@property (assign, nonatomic) BOOL isActiveSpinner;

@property (assign, nonatomic) NSInteger spinnerLinks;
@property (assign, nonatomic) NSInteger statusSpinnerLinks;
@property (assign, nonatomic) double secForDelayNotification;

@end

@implementation SGSAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    /*self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];*/
    
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
#if CLEAR_SETTINGS
    [[GSModelsManager sharedModelsManager] clearSettings];
#endif
    
#if CLEAR_EVENTS
    [[GSModelsManager sharedModelsManager] deleteAllEventsFromLocalDB];
#endif
    
#if CLEAR_CONTACTS
    [[GSModelsManager sharedModelsManager] deleteAllContactsFromLocalDB];
#endif
    
#if CLEAR_MYPROFILE
    [[GSModelsManager sharedModelsManager] deleteMyProfileFromLocalDB];
#endif
    
#if CHECK_STORED_TOKEN
    [[GSModelsManager sharedModelsManager] loadSettings];
#endif
    
    
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(
                                                                                                    UIUserNotificationTypeSound
                                                                                                    | UIUserNotificationTypeAlert
                                                                                                    | UIUserNotificationTypeBadge) categories:nil]];
        
        [application registerForRemoteNotifications];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (
                                                                                UIRemoteNotificationTypeBadge
                                                                                | UIRemoteNotificationTypeSound
                                                                                | UIRemoteNotificationTypeAlert
                                                                                )];
    }
    
    [modelsManager loadSettings];
    [modelsManager saveSettings];
    
    self.secForDelayNotification = 3;
    
    self.isActiveSpinner = NO;
    
    self.spinnerLinks = 0;
    self.statusSpinnerLinks = 0;
    
    return YES;
}

-(void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    GSLog(GSLogSystem, @"Device token: %@", deviceToken);
    
    [[SGSModelsManager sharedModelsManager] saveDeviceToken:deviceToken];
}

-(void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    GSLog(GSLogError, @"Failed to get token, error: %@", error);
    [[SGSModelsManager sharedModelsManager] saveDeviceTokenError:error.localizedDescription];
}

-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    GSLog(GSLogSystem, @"Received notification: %@", userInfo);
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW , (int64_t)(self.secForDelayNotification * NSEC_PER_SEC ));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void ) {
        
        self.secForDelayNotification = 0;
        [[NSNotificationCenter defaultCenter] postNotificationName:receivedRemoteNotification object:nil userInfo:userInfo];
        
    });
    
    GSLog(GSLogEvent, @"----- Application Did Receive Remote Notification");
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    GSLog(GSLogEvent, @"----- Application Did Become Active");
    
    [self application:application didReceiveRemoteNotification:nil];
#if SYNCHRONIZE_DB
    [[SGSModelsManager sharedModelsManager] synchronizeDB];
#endif
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    GSLog(GSLogEvent, @"----- Application Will Terminate");
    
    [[SGSModelsManager sharedModelsManager] saveSettings];

}

#pragma mark - Spinner

-(void) startSpinner {
    
    self.spinnerLinks++;
    
    if (!self.isActiveSpinner) {
        
        self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
        self.spinner.center = self.window.rootViewController.view.center;
        
        [self.window.rootViewController.view addSubview:self.spinner];
        
        [self.spinner startAnimating];
        
        self.isActiveSpinner = YES;
    }
}

-(void) stopSpinner {
    
    self.spinnerLinks--;
    
    if ((self.isActiveSpinner) && (self.spinnerLinks<=0)) {
        [self.spinner stopAnimating];
        
        [self.spinner removeFromSuperview];
        
        self.spinner = nil;
        
        self.isActiveSpinner = NO;
    }
}

-(void) startStatusBarSpinner {
    self.statusSpinnerLinks++;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

-(void) stopStatusBarSpinner {
    self.statusSpinnerLinks--;
    
    if (self.statusSpinnerLinks<=0) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }
}


// During the Facebook login flow, your app passes control to the Facebook iOS app or Facebook in a mobile browser.
// After authentication, your app will be called back with the session information.
// Override application:openURL:sourceApplication:annotation to call the FBsession object that handles the incoming URL
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    GSLog(GSLogEvent, @"[UIApplication] Received URL: %@", url);
    
    if ([url.scheme hasPrefix:@"fb"]) {
        //Facebook callback
        return [FBSession.activeSession handleOpenURL:url];
    } else {
        //GooglePlus callback
        return [GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation];
    }
}

@end
